package com.ee.chat.common.service.impl;

import com.ee.chat.common.dao.*;
import com.ee.chat.common.entity.*;
import com.ee.chat.common.service.IYieldService;
import com.ndhutu.ee.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * @Author Shane
 * @Date 2020/1/30 20:10
 */
@Service
public class YieldServiceImpl implements IYieldService {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource
    UserInviteLogMapper userInviteLogMapper;
    @Resource
    ChannelUserLogMapper channelUserLogMapper;
    @Resource
    SysConfigMapper sysConfigMapper;
    @Resource
    UserWalletMapper userWalletMapper;
    @Resource
    UserCreditLogMapper userCreditLogMapper;
    @Resource
    UserRechargeLogMapper userRechargeLogMapper;
    @Resource
    ChannelMapper channelMapper;
    @Resource
    ChannelEarnMapper channelEarnMapper;
    @Resource
    UserCoinLogMapper userCoinLogMapper;
    @Resource
    HostMapper hostMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    UserAuditLogMapper userAuditLogMapper;
    @Resource
    UserConsumeLogMapper userConsumeLogMapper;

    /**
     * 用户消费
     * @Author Shane
     * @Date 2019/11/16 11:14
     * @param userId    用户id
     * @param type      消费类型
     * @param toUserId  主播id
     * @param buyId     关联id
     * @param coin      消费金币
     * @param credit    获取积分
     * @return
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void consume(Integer userId, Integer type, Integer toUserId, String buyId, Integer coin, Double credit) throws Exception{
        //添加消费记录
        UserConsumeLog userConsumeLog = new UserConsumeLog(userId, type, toUserId, buyId, coin, credit);
        userConsumeLogMapper.insert(userConsumeLog);

        boolean flag = true;

        String desc1 = null, desc2 = null;
        switch (type){
            case 0:
                desc1 = "视频通话";
                desc2 = "视频通话";
                flag = false;
                break;
            case 1:
                desc1 = "解锁动态";
                desc2 = "动态被解锁";
                break;
            case 2:
                desc1 = "文字聊天";
                desc2 = "文字聊天";
                break;
            case 3:
            case 4:
            case 5:
            case 6:
                desc1 = "赠送礼物";
                desc2 = "收到礼物";
                break;
            case 7:
                desc1 = "语音聊天";
                desc2 = "语音聊天";
                break;
        }

        //更新用户钱包
        updateUserWallet(userId, userConsumeLog.getId(), 1, -coin.doubleValue(), desc1, 0);

        //更新主播钱包
        updateUserWallet(toUserId, userConsumeLog.getId(), 0, credit, desc2, 1);

        //处理邀请奖励
        if(flag){
            handlePopYield(toUserId, 1, userConsumeLog.getCredit(), userConsumeLog.getId());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserWallet(Integer userId, Integer consumId, Integer type, Double num, String desc, Integer walletType) throws Exception{
        if(num == 0){
            return;
        }

        UserWallet userWallet = userWalletMapper.getByUserId(userId);
        if(userWallet == null){
            userWallet = new UserWallet(userId, 0, 0, 0.0, 0.0);
        }

        //添加记录
        if(walletType == 0){
            UserCoinLog userCoinLog = new UserCoinLog(userId, consumId, type, num.intValue(), desc);
            userCoinLogMapper.insert(userCoinLog);

            if(num > 0){
                userWallet.setTotalCoin(userWallet.getTotalCoin() + num.intValue());
            }
            userWallet.setActiveCoin(userWallet.getActiveCoin() + num.intValue());
        }else if(walletType == 1){
            UserCreditLog userCreditLog = new UserCreditLog(userId, consumId, type, num, desc);
            userCreditLogMapper.insert(userCreditLog);

            if(num > 0){
                userWallet.setTotalCredit(userWallet.getTotalCredit() + num);
            }
            userWallet.setActiveCredit(userWallet.getActiveCredit() + num);
        }else{
            return;
        }

        //更新钱包
        if(userWallet.getId() == null){
            userWalletMapper.insert(userWallet);
        }else{
            userWalletMapper.updateById(userWallet);
        }
    }

    /**
     * 处理推广收益
     * @Author Shane
     * @Date 2020/4/10 15:01
     * @param userId    用户id
     * @param ogUserId  原始用户id（用于记录收益明细时收益原始产生者）
     * @param type  类型，0-充值  1-收入  2-购买会员
     * @param amount    总金额，单位分
     * @param consumId  关联记录id
     * @param num   循环次数，默认为0
     * @param rate  比例，默认为0
     * @return
     */
    private void handlePopYield(Integer userId, Integer ogUserId,  Integer type, Double amount, Integer consumId, Integer num, double rate) throws Exception{
        //积分兑换比例
        String money_to_credit_rate = sysConfigMapper.getValue("money_to_credit_rate");

        Integer inviteUserId = null;
        boolean flag = false;

        double rate1 = 0;

        /***********************************app邀请用户begin*********************************************************/
        UserInviteLog userInviteLog = userInviteLogMapper.selectByUserId(userId);
        if(userInviteLog != null){
            inviteUserId = userInviteLog.getInviteUserId();
            if(type == 0){  //充值
                rate1 = Double.parseDouble(sysConfigMapper.getValue("app_first_invite_recharge_rate"));
                rate = rate1 - rate;
                flag = true;
            }else if(type == 1){    //收入
                if(num == 0){
                    rate = Double.parseDouble(sysConfigMapper.getValue("app_first_invite_rate"));
                    flag = true;
                }else if(num == 1){
                    rate = Double.parseDouble(sysConfigMapper.getValue("app_second_invite_rate"));
                    flag = true;
                }else{
                    return;
                }
            }else if(type == 2 && num == 0){    //购买会员
                rate = Double.parseDouble(sysConfigMapper.getValue("app_first_invite_vip_rate"));
                flag = true;
            }else{
                return;
            }
        }
        /***********************************app邀请用户end*********************************************************/


        /***********************************渠道邀请用户begin*********************************************************/
        Channel channel = channelUserLogMapper.getUserInviteChannel(userId);
        if(channel == null){
            Channel temp = channelMapper.selectByUserId(userId);
            if(temp != null && temp.getPid() != 0){
                channel = channelMapper.selectById(temp.getPid());
            }
        }
        if(channel != null){
            inviteUserId = channel.getUserId();

            //主播渠道
            if(channel.getType() == 1){
                if(type == 0){  //充值
                    if(num == 0){
                        rate = channelEarnMapper.selectValue(channel.getId(), "first_invite_recharge_rate");
                        flag = true;
                    }else if(num == 1){
                        rate = channelEarnMapper.selectValue(channel.getId(), "second_invite_recharge_rate");
                        flag = true;
                    }else{
                        return;
                    }
                }else if(type == 1){    //收入
                    if(num == 0){
                        rate = channelEarnMapper.selectValue(channel.getId(), "first_invite_rate");
                        flag = true;
                    }else if(num == 1){
                        rate = channelEarnMapper.selectValue(channel.getId(), "second_invite_rate");
                        flag = true;
                    }else {
                        return;
                    }
                }else if(type == 2 && num == 0){    //购买会员
                    rate = channelEarnMapper.selectValue(channel.getId(), "first_invite_vip_rate");
                    flag = true;
                }else {
                    return;
                }

            //cps渠道
            }else if(channel.getType() == 2){  //cps渠道
                if(type == 0){  //充值
                    //只能获取直接邀请的
                    if(num >= 1 && channelMapper.selectByUserId(userId) == null){
                        return;
                    }
                    rate1 = channelEarnMapper.selectValue(channel.getId(), "first_invite_recharge_rate");
                    rate = rate1 - rate;
                    flag = true;
                }else if(type == 1){    //收入
                    if(num == 0){
                        rate = channelEarnMapper.selectValue(channel.getId(), "first_invite_rate");
                        flag = true;
                    }else if(num == 1){
                        rate = channelEarnMapper.selectValue(channel.getId(), "second_invite_rate");
                        flag = true;
                    }else {
                        return;
                    }
                }else if(type == 2){    //购买会员
                    //只能获取直接邀请的
                    if(num >= 1 && channelMapper.selectByUserId(userId) == null){
                        return;
                    }
                    rate1 = channelEarnMapper.selectValue(channel.getId(), "first_invite_vip_rate");
                    rate = rate1 - rate;
                    flag = true;
                }else{
                    return;
                }
            }else if(channel.getType() == 3){   //工会渠道
                if(type == 0){  //充值
                    rate1 = channelEarnMapper.selectValue(channel.getId(), "first_invite_recharge_rate");
                    rate = rate1 - rate;
                    flag = true;
                }else if(type == 1){    //收入
                    if(num == 0){
                        rate = channelEarnMapper.selectValue(channel.getId(), "first_invite_rate");
                        flag = true;
                    }else if(num == 1){
                        rate = channelEarnMapper.selectValue(channel.getId(), "second_invite_rate");
                        flag = true;
                    }else {
                        return;
                    }
                }else if(type == 2 && num == 0){    //购买会员
                    rate = channelEarnMapper.selectValue(channel.getId(), "first_invite_vip_rate");
                    flag = true;
                }else{
                    return;
                }
            }
        }

        /***********************************渠道邀请用户end*********************************************************/

        if(!flag){
            return;
        }

        //计算收益
        double credit = 0.0;
        if(type == 1){  //积分
            credit = new BigDecimal(amount+"").multiply(new BigDecimal(rate+""))
                    .divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP).doubleValue();
        }else{  //钱
            credit = new BigDecimal(amount+"").multiply(new BigDecimal(rate+"")).multiply(new BigDecimal(money_to_credit_rate))
                    .divide(new BigDecimal("10000"), 2, BigDecimal.ROUND_HALF_UP).doubleValue();
        }

        //收益不为空
//        if(credit < 0){ //异常情况
//            log.error("存在异常收益比例情况，用户："+userId+"，原始用户："+ogUserId+"，类型："+type+"，关联记录id："+consumId);
//            return;
//        }
        if(credit > 0){
            Integer creditLogType = null;
            String desc = null;
            if(type == 0){
                if(num == 0){
                    creditLogType = 1;
                }else{
                    creditLogType = 9;
                }
            }else if(type == 1){
                if(num == 0){
                    creditLogType = 6;
                }else {
                    creditLogType = 7;
                }
            }else if(type == 2){
                creditLogType = 10;
            }
            if(num == 0){
                desc = "直接邀请的用户"+ogUserId+"产生的收益";
            }else{
                desc = "间接邀请的用户"+ogUserId+"产生的收益";
            }

            //更新收益
            updateUserWallet(inviteUserId, consumId, creditLogType, credit, desc, 1);

        }

        num ++;
        if(rate < 0){
            rate = rate1 - rate;
        }else if(rate >= 0){
            rate = rate1;
        }

        handlePopYield(inviteUserId, ogUserId, type, amount, consumId, num, rate);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handlePopYield(Integer userId, Integer type, Double amount, Integer consumId) throws Exception{
        handlePopYield(userId, userId, type, amount, consumId, 0 , 0);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleInviteRegYield(Integer userId) throws Exception{
        User user = userMapper.selectById(userId);
        if(user.getGender() == 1){
            Integer inviteUserId = null, type = null;

            UserInviteLog userInviteLog = userInviteLogMapper.selectByUserId(userId);
            if(userInviteLog != null){
                inviteUserId = userInviteLog.getInviteUserId();
                type = 0;
            }else{
                Channel channel = channelUserLogMapper.getUserInviteChannel(userId);
                if(channel != null){
                    inviteUserId = channel.getUserId();
                    if(channel.getType() == 1){
                        type = 1;
                    }else if(channel.getType() == 3){
                        type = 2;
                    }
                }
            }

            if(inviteUserId != null && type != null){

                //人头将被取消
                User inviteUser = userMapper.selectById(inviteUserId);
               /* if(inviteUser.getInvitePeopleAward() == 1){
                    return;
                }*/

                double rate = Double.parseDouble(sysConfigMapper.getValue("money_to_credit_rate"));
                double credit = 0, money = 0;
                if(type == 0){
                    money = Double.parseDouble(sysConfigMapper.getValue("app_first_invite_user_rate"));
                }else if(type == 1){
                    Channel channel = channelMapper.selectByUserId(inviteUserId);
                    money = channelEarnMapper.selectValue(channel.getId(), "first_invite_user_rate");
                }else if(type == 2){
                    Channel channel = channelMapper.selectByUserId(inviteUserId);
                    money = channelEarnMapper.selectValue(channel.getId(), "first_invite_user_rate");
                }else{
                    return;
                }

                credit = rate * money;
                int creditLogType = 11;
                String desc = "直接邀请"+userId+"男用户注册获取收益";

                //更新收益
                updateUserWallet(inviteUserId, userId, creditLogType, credit, desc, 1);
            }
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleActivityYield(Integer userId, Integer consumId, Integer type, Date dete) throws Exception{
        String activityTime = sysConfigMapper.getValue("activity_time");

        //比较活动时间
        Date beginTime = DateUtil.parse(activityTime.split("~")[0]);
        Date endTime = DateUtil.parse(activityTime.split("~")[1]);
        Date now = new Date();
        if(now.compareTo(beginTime) < 0 || now.compareTo(endTime) > 0){
            return;
        }

        //获取邀请者
        Integer inviteUserId = null;
        UserInviteLog userInviteLog = userInviteLogMapper.selectByUserId(userId);
        if(userInviteLog != null){
            inviteUserId = userInviteLog.getInviteUserId();
        }else{
            Channel channel = channelUserLogMapper.getUserInviteChannel(userId);
            if(channel != null){
                inviteUserId = channel.getUserId();
            }else{
                channel = channelMapper.selectByUserId(userId);
                if(channel != null){
                    channel = channelMapper.selectById(channel.getPid());
                    if(channel != null){
                        inviteUserId = channel.getUserId();
                    }
                }
            }
        }
        if(inviteUserId == null){
            return;
        }
        //判断是否禁用人头奖
        User inviteUser = userMapper.selectById(inviteUserId);
       /* if(inviteUser.getInvitePeopleAward() == 1){
            return;
        }*/

        User user = userMapper.selectById(userId);
        Host host = hostMapper.selectByUserId(userId);
        int count = userRechargeLogMapper.getUserRechargeCount(userId);

        int auditCount = userAuditLogMapper.getAccecptCount(userId, 0);

        Double credit = 0.0, money = 0.0;
        Integer creditLogType = null;
        String desc = null;
        if(type == 0 && count == 1 && host == null && (user.getGender() != null && user.getGender() == 1)){
            //男用户第一笔充值
            money = Double.parseDouble(sysConfigMapper.getValue("activity_top_recharge_award"));
            creditLogType = 1;
            desc = "活动期间，直接邀请的男用户完成第一笔充值的奖励";

        }else if(type == 1 && auditCount == 0 && (user.getGender() == null || user.getGender() == 0)){
            //女用户第一次认证成功
            money = Double.parseDouble(sysConfigMapper.getValue("activity_audit_award"));
            creditLogType = 8;
            desc = "活动期间，直接邀请的女用户完成认证获得的奖励";

        }else{
            return;
        }

        double rate = Double.parseDouble(sysConfigMapper.getValue("money_to_credit_rate"));
        credit = rate * money;

        updateUserWallet(inviteUserId, consumId, creditLogType, credit, desc, 1);
    }

}
